package cn.mujiankeji.mbrowser.界面.框架.主视图

import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets // 用于处理状态栏/导航栏遮挡
import androidx.compose.foundation.layout.asPaddingValues // 用于处理状态栏/导航栏遮挡
import androidx.compose.foundation.layout.fillMaxSize // For matchParentSize replacement
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars // 用于处理状态栏/导航栏遮挡
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button // 可以继续使用 Button 或 TextButton
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet // 导入 ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState // 导入 rememberModalBottomSheetState
import androidx.compose.material3.SwipeToDismissBox // M3
import androidx.compose.material3.SwipeToDismissBoxValue // M3
import androidx.compose.material3.rememberSwipeToDismissBoxState // M3
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope // 用于控制 sheetState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.app.应用组件.应用图片
import cn.mujiankeji.mbrowser.界面.图标.MyIconPack
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.删除
import cn.mujiankeji.mbrowser.app.界面模块
import cn.mujiankeji.mbrowser.工具.mlog
import kotlinx.coroutines.launch // 用于控制 sheetState
import org.koin.compose.koinInject

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun 窗口列表面板( // 重命名，并调整参数
    显示: Boolean, // 新增参数控制是否显示
    viewModel: 界面模块 = koinInject(),
    onDismissRequest: () -> Unit
) {
    val 窗口列表 = viewModel.窗口列表 // 直接使用 mutableStateListOf
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) // 底部面板状态，跳过半展开
    val scope = rememberCoroutineScope()

    // 当外部请求显示/隐藏时，命令式地控制 BottomSheet
    LaunchedEffect(显示) {
        if (显示) {
            scope.launch { sheetState.show() }
        } else {
            scope.launch { sheetState.hide() }.invokeOnCompletion {
                if (!sheetState.isVisible) { // 确保在动画完成后才回调
                    onDismissRequest()
                }
            }
        }
    }
    
    // 当用户通过手势等方式关闭 BottomSheet 时，回调 onDismissRequest
    // 注意：如果 sheetState.isVisible 从 true 变为 false，则认为是用户关闭了它
    // if (显示 && !sheetState.isVisible && sheetState.hasExpandedState) { // hasExpandedState 确保不是初始状态
    //      LaunchedEffect(sheetState.isVisible) { // 监听 isVisible 变化
    //          if(!sheetState.isVisible) onDismissRequest()
    //      }
    // }


    if (显示) { // 只有在外部请求显示时，才渲染 ModalBottomSheet
        ModalBottomSheet(
            onDismissRequest = onDismissRequest, // 当点击外部或返回键时触发
            sheetState = sheetState,
            // windowInsets = WindowInsets.navigationBars, // 考虑导航栏遮挡
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .padding(WindowInsets.navigationBars.asPaddingValues()) // 确保内容不被导航栏遮挡
            ) {


                LazyColumn(modifier = Modifier.
                fillMaxWidth().weight(1f, fill = false)) { // weight 防止无限高度
                    itemsIndexed(窗口列表, key = { _, item -> item.id }) { index, 窗口 ->
                        val dismissState = rememberSwipeToDismissBoxState(
                            confirmValueChange = { dismissValue ->
                                if (dismissValue == SwipeToDismissBoxValue.EndToStart || dismissValue == SwipeToDismissBoxValue.StartToEnd) {
                                    handleWindowRemoval(viewModel, 窗口.id)
                                    true
                                } else {
                                    false
                                }
                            },
                            positionalThreshold = { it * .25f } // Example threshold
                        )

                        SwipeToDismissBox(
                            state = dismissState,
                            backgroundContent = {
                                val color = when (dismissState.dismissDirection) {
                                    SwipeToDismissBoxValue.EndToStart -> Color.Red.copy(alpha = 0.8f)
                                    SwipeToDismissBoxValue.StartToEnd -> Color.Red.copy(alpha = 0.8f)
                                    SwipeToDismissBoxValue.Settled -> Color.Transparent // Or other default
                                }
                                val alignment = when (dismissState.dismissDirection) {
                                    SwipeToDismissBoxValue.EndToStart -> Alignment.CenterEnd
                                    SwipeToDismissBoxValue.StartToEnd -> Alignment.CenterStart
                                    SwipeToDismissBoxValue.Settled -> Alignment.Center // Default alignment
                                }
                                val icon = MyIconPack.删除 // Using a more common delete icon
                                val scale by animateFloatAsState(
                                    targetValue = if (dismissState.targetValue != SwipeToDismissBoxValue.Settled) 1.2f else 0.8f,
                                    label = "dismiss scale animation"
                                )

                                Box(
                                    modifier = Modifier
                                        .fillMaxSize() // Replaced matchParentSize
                                        .background(color)
                                        .padding(horizontal = 20.dp), // Increased padding for visibility
                                    contentAlignment = alignment
                                ) {
                                    Icon(
                                        icon,
                                        contentDescription = "删除窗口",
                                        modifier = Modifier.scale(scale),
                                        tint = Color.White
                                    )
                                }
                            },
                            content = {
                                // Determine if the current item in the list is the active window
                                val isCurrentlyActive = viewModel.当前活动窗口.collectAsState().value?.id == 窗口.id
                                WindowItem(
                                    窗口 = 窗口,
                                    isCurrentWindow = isCurrentlyActive, // Pass boolean based on ID check
                                    onWindowClick = {
                                        viewModel.切换窗口(index)
                                        scope.launch { sheetState.hide() }
                                            .invokeOnCompletion { onDismissRequest() }
                                    },
                                    onDeleteClick = {
                                        handleWindowRemoval(viewModel, 窗口.id)
                                    }
                                )
                            },
                            enableDismissFromStartToEnd = true,
                            enableDismissFromEndToStart = true,
                            modifier = Modifier.clip(MaterialTheme.shapes.medium)
                        )

                        Spacer(Modifier.height(10.dp))
                    }
                }
                
                Spacer(modifier = Modifier.height(16.dp))
                
                Button( // 使用填充按钮更醒目
                    onClick = {
                        viewModel.创建窗口()
                    },
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Icon(
                        Icons.Default.Add,
                        contentDescription = null,
                        modifier = Modifier.padding(end = 8.dp)
                    )
                    Text("添加新窗口")
                }

            }
        }
    }
}

@Composable
private fun WindowItem(
    窗口: 窗口页状态,
    isCurrentWindow: Boolean, // Use this to determine style
    onWindowClick: () -> Unit,
    onDeleteClick: () -> Unit
) {
    val 活动标签 = 窗口.当前活动标签页.collectAsState().value
    val 窗口标题 = 活动标签?.标题?.collectAsState()?.value ?: "窗口 (${窗口.id.takeLast(6)})"
    val 窗口地址 = 活动标签?.地址?.collectAsState()?.value?: "--"
    val 窗口图标 = 活动标签?.图标?.collectAsState()?.value?:""
    
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clip(MaterialTheme.shapes.medium)
            .background(MaterialTheme.colorScheme.surface) // Ensure content has a background for swipe
            .clickable(onClick = onWindowClick)
            .padding(vertical = 12.dp, horizontal = 16.dp), // Added horizontal padding
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {

        应用图片(窗口图标, modifier = Modifier.size(28.dp))

        Spacer(Modifier.width(15.dp))

        Column(Modifier.weight(1f)) {
            Text(
                text = 窗口标题,
                style = if (isCurrentWindow) MaterialTheme.typography.titleSmall
                else MaterialTheme.typography.bodyMedium,
                maxLines = 1
            )
            Spacer(Modifier.height(3.dp))
            Text(text = 窗口地址,
                style = MaterialTheme.typography.labelMedium,
                maxLines = 1)

        }



        IconButton(
            onClick = onDeleteClick,
            modifier = Modifier.size(28.dp)
        ) {
            Icon(
                Icons.Filled.Close, // Using Filled.Close as per original
                contentDescription = "关闭窗口",
                tint = MaterialTheme.colorScheme.outline,
                modifier = Modifier.size(16.dp)
            )
        }
    }
}

// 处理窗口移除的逻辑
private fun handleWindowRemoval(viewModel: 界面模块, 窗口ID: String) {
    viewModel.移除窗口(窗口ID) 
    // The ViewModel's 移除窗口 method now handles the logic for selecting the next active window.
    // No further logic needed here for that.
} 